import {createStore} from '@/airstore';
import ApiClient from '@/services/apiClient';

const initialShipRequester = {
  tid: null,
  name: '',
  department: '',
};
export default createStore({
  namespace: 'RackMaterialStore',
  shipRequester: initialShipRequester,
  currentRack: {},
  scannedParts: [], // {rack_no, qty, part_no}
  partqtyModal: {
    visible: false,
    qty: 1,
    earlierParts: [],
    material: null,
  },
  setCurrentRack(rack) {
    this.currentRack = rack;
  },
  setShipRequester(shipRequster) {
    this.shipRequester = shipRequster;
  },
  showPartQtyModal(partqtyModal) {
    this.partqtyModal = {...this.partqtyModal, ...partqtyModal};
  },
  hidePartQtyModal() {
    this.partqtyModal = {visible: false, qty: 1};
  },
  addScannedPart(scanPart) {
    const existPartIdx = this.scannedParts.findIndex(
      (scnp) =>
        scnp.rack_no === scanPart.rack_no && scnp.part_no === scanPart.part_no,
    );
    if (existPartIdx !== -1) {
      this.scannedParts.splice(existPartIdx, 1);
    }
    this.scannedParts = [scanPart].concat(this.scannedParts.slice(0, 1));
  },
  clearScannedData() {
    this.currentRack = {};
    this.scannedParts = [];
  },
  clearShipRequester() {
    this.shipRequester = initialShipRequester;
  },
  async getRackByTid(tid) {
    const rackRes = await ApiClient.get(`amStore/v1/getBydefine/${tid}`);
    if (!rackRes.errorCode) {
      this.setCurrentRack({
        tid: rackRes.data.tid,
        rackName: rackRes.data.storeName,
        shelfName: rackRes.data.asdSubName,
      });
      /*
    this.setCurrentRack({
      tid,
      name: '2车间/3架位',
    });
    return {};
    */
    }
    return rackRes;
  },
  async getShipRequester(tid) {
    const srRes = await ApiClient.get(`amUser/v1/getInnerUserById/${tid}`);
    if (!srRes.errorCode) {
      this.setShipRequester({
        tid,
        name: srRes.data.userName,
        department: srRes.data.deptName,
      });
      /*
    this.setShipRequester({
      tid: 2,
      name: 'sombody',
      department: 'dept1',
    });
    */
    }
    return srRes.errorMsg;
  },
});
